<template>
  <div class="app-container">
    <el-card shadow="hover" v-loading="loading">
      <template #header>
        <div class="card-header">
          <div class="header-left">
            <h3>库存详情</h3>
            <el-tag v-if="inventoryData.status" :type="getStatusTagType(inventoryData)">
              {{ getStatusLabel(inventoryData) }}
            </el-tag>
          </div>
          <div>
            <el-button @click="goBack">返回</el-button>
            <el-button
              type="warning"
              @click="handleUpdateInventory"
              v-permission="'drug_inventory:update'"
              :disabled="isExpired(inventoryData.expiryDate)"
            >
              调整库存
            </el-button>
            <el-button
              type="danger"
              @click="handleDiscard"
              v-permission="'drug_inventory:update'"
              :disabled="inventoryData.quantity <= 0"
            >
              报废
            </el-button>
          </div>
        </div>
      </template>

      <!-- 药品基本信息 -->
      <div class="info-section">
        <h4 class="section-title">药品信息</h4>
        <el-descriptions :column="3" border>
          <el-descriptions-item label="药品名称">
            {{ inventoryData.drugName }}
          </el-descriptions-item>
          <el-descriptions-item label="药品编码">
            {{ inventoryData.drugCode }}
          </el-descriptions-item>
          <el-descriptions-item label="规格">
            {{ inventoryData.specification }}
          </el-descriptions-item>
          <el-descriptions-item label="剂型">
            {{ inventoryData.dosageForm }}
          </el-descriptions-item>
          <el-descriptions-item label="分类">
            <el-tag size="small">{{ inventoryData.category }}</el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="销售单价">
            {{ formatCurrency(inventoryData.price) }}
          </el-descriptions-item>
          <el-descriptions-item label="生产厂家" :span="3">
            {{ inventoryData.manufacturer }}
          </el-descriptions-item>
        </el-descriptions>
      </div>

      <!-- 库存批次信息 -->
      <div class="info-section">
        <h4 class="section-title">库存批次信息</h4>
        <el-descriptions :column="3" border>
          <el-descriptions-item label="批次号">
            {{ inventoryData.batchNumber }}
          </el-descriptions-item>
          <el-descriptions-item label="当前库存">
            <span class="inventory-count">
              {{ inventoryData.quantity }} {{ inventoryData.unit }}
            </span>
          </el-descriptions-item>
          <el-descriptions-item label="采购单价">
            {{ formatCurrency(inventoryData.purchasePrice) }}
          </el-descriptions-item>
          <el-descriptions-item label="生产日期">
            {{ inventoryData.productionDate }}
          </el-descriptions-item>
          <el-descriptions-item label="有效期至">
            <span :class="getExpiryClass(inventoryData)">
              {{ inventoryData.expiryDate }}
              <el-tag v-if="!isExpired(inventoryData.expiryDate) && isNearExpiry(inventoryData.expiryDate)" 
                      type="warning" size="small">
                剩余 {{ calculateRemainingDays(inventoryData.expiryDate) }} 天
              </el-tag>
              <el-tag v-if="isExpired(inventoryData.expiryDate)" 
                      type="danger" size="small">
                已过期 {{ Math.abs(calculateRemainingDays(inventoryData.expiryDate)) }} 天
              </el-tag>
            </span>
          </el-descriptions-item>
          <el-descriptions-item label="采购日期">
            {{ inventoryData.purchaseDate }}
          </el-descriptions-item>
          <el-descriptions-item label="供应商" :span="3">
            {{ inventoryData.supplier || '未知' }}
          </el-descriptions-item>
        </el-descriptions>
      </div>

      <!-- 库存变动记录 -->
      <div class="info-section">
        <h4 class="section-title">库存变动记录</h4>
        <el-table
          :data="inventoryHistory"
          style="width: 100%"
          border
          stripe
          :empty-text="historyLoading ? '加载中...' : '暂无库存变动记录'"
          v-loading="historyLoading"
        >
          <el-table-column prop="date" label="操作时间" width="180" />
          <el-table-column prop="type" label="操作类型" width="120">
            <template #default="scope">
              <el-tag :type="getOperationTagType(scope.row.type)">
                {{ getOperationLabel(scope.row.type) }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="quantity" label="数量变化" width="120">
            <template #default="scope">
              <span :class="scope.row.quantity >= 0 ? 'quantity-increase' : 'quantity-decrease'">
                {{ scope.row.quantity > 0 ? '+' : '' }}{{ scope.row.quantity }} {{ inventoryData.unit }}
              </span>
            </template>
          </el-table-column>
          <el-table-column prop="reason" label="操作原因" width="120">
            <template #default="scope">
              {{ getReasonLabel(scope.row.reason, scope.row.type) }}
            </template>
          </el-table-column>
          <el-table-column prop="operator" label="操作人" width="120" />
          <el-table-column prop="remark" label="备注" min-width="200" show-overflow-tooltip />
          <el-table-column prop="balance" label="操作后库存" width="120">
            <template #default="scope">
              {{ scope.row.balance }} {{ inventoryData.unit }}
            </template>
          </el-table-column>
        </el-table>
      </div>
    </el-card>

    <!-- 库存调整对话框 -->
    <el-dialog
      title="库存调整"
      v-model="inventoryDialog.visible"
      width="500px"
    >
      <el-form :model="inventoryDialog.form" label-width="120px" ref="inventoryFormRef">
        <el-form-item label="药品名称">
          <el-input v-model="inventoryDialog.form.drugName" disabled />
        </el-form-item>
        <el-form-item label="批次号">
          <el-input v-model="inventoryDialog.form.batchNumber" disabled />
        </el-form-item>
        <el-form-item label="当前库存">
          <el-input v-model="inventoryDialog.form.currentQuantity" disabled>
            <template #append>{{ inventoryDialog.form.unit }}</template>
          </el-input>
        </el-form-item>
        <el-form-item label="调整数量" prop="adjustQuantity">
          <el-input-number 
            v-model="inventoryDialog.form.adjustQuantity" 
            :min="-inventoryDialog.form.currentQuantity" 
            :max="1000"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="调整原因" prop="reason">
          <el-select v-model="inventoryDialog.form.reason" placeholder="请选择调整原因" style="width: 100%">
            <el-option label="盘盈" value="surplus" />
            <el-option label="盘亏" value="loss" />
            <el-option label="损耗" value="damage" />
            <el-option label="其他" value="other" />
          </el-select>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input 
            v-model="inventoryDialog.form.remark" 
            type="textarea" 
            :rows="3" 
            placeholder="请输入备注信息" 
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="inventoryDialog.visible = false">取消</el-button>
          <el-button type="primary" @click="confirmInventoryAdjust" :loading="inventoryDialog.loading">
            确认
          </el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 报废对话框 -->
    <el-dialog
      title="药品报废"
      v-model="discardDialog.visible"
      width="500px"
    >
      <el-form :model="discardDialog.form" label-width="120px" ref="discardFormRef">
        <el-form-item label="药品名称">
          <el-input v-model="discardDialog.form.drugName" disabled />
        </el-form-item>
        <el-form-item label="批次号">
          <el-input v-model="discardDialog.form.batchNumber" disabled />
        </el-form-item>
        <el-form-item label="当前库存">
          <el-input v-model="discardDialog.form.currentQuantity" disabled>
            <template #append>{{ discardDialog.form.unit }}</template>
          </el-input>
        </el-form-item>
        <el-form-item label="报废数量" prop="discardQuantity">
          <el-input-number 
            v-model="discardDialog.form.discardQuantity" 
            :min="1" 
            :max="discardDialog.form.currentQuantity"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="报废原因" prop="reason">
          <el-select v-model="discardDialog.form.reason" placeholder="请选择报废原因" style="width: 100%">
            <el-option label="过期" value="expired" />
            <el-option label="质量问题" value="quality" />
            <el-option label="包装破损" value="damaged" />
            <el-option label="其他" value="other" />
          </el-select>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input 
            v-model="discardDialog.form.remark" 
            type="textarea" 
            :rows="3" 
            placeholder="请输入备注信息" 
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="discardDialog.visible = false">取消</el-button>
          <el-button type="danger" @click="confirmDiscard" :loading="discardDialog.loading">
            确认报废
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { ElMessage } from 'element-plus'
import { drugInventoryAPI } from '@/utils/api'
import { formatCurrency } from '@/utils/format'

const router = useRouter()
const route = useRoute()
const inventoryId = route.params.id

const loading = ref(true)
const historyLoading = ref(true)
const inventoryData = reactive({})
const inventoryHistory = ref([])

// 库存调整对话框
const inventoryDialog = reactive({
  visible: false,
  loading: false,
  form: {
    id: '',
    drugName: '',
    batchNumber: '',
    currentQuantity: 0,
    adjustQuantity: 0,
    unit: '',
    reason: '',
    remark: ''
  }
})

// 报废对话框
const discardDialog = reactive({
  visible: false,
  loading: false,
  form: {
    id: '',
    drugName: '',
    batchNumber: '',
    currentQuantity: 0,
    discardQuantity: 0,
    unit: '',
    reason: '',
    remark: ''
  }
})

// 获取库存详情
const fetchInventoryDetail = async () => {
  loading.value = true
  try {
    const res = await drugInventoryAPI.getInventory(inventoryId)
    if (res.data && res.data.success) {
      const data = res.data.data.inventory
      
      // 填充库存数据
      Object.assign(inventoryData, data)
      
      // 设置状态标签
      inventoryData.status = getStatusLabel(inventoryData)
    } else {
      ElMessage.error(res.data.message || '获取库存详情失败')
    }
  } catch (error) {
    console.error('获取库存详情失败', error)
    ElMessage.error('获取库存详情失败')
  } finally {
    loading.value = false
  }
}

// 获取库存历史记录
const fetchInventoryHistory = async () => {
  historyLoading.value = true
  try {
    // 这里假设后端API提供了获取库存历史记录的接口
    // 实际上可能需要通过其他接口获取，或者在inventory详情中已经包含了历史记录
    // 这里为了演示，我们使用模拟数据
    
    // 模拟API调用
    // const res = await drugInventoryAPI.getInventoryHistory(inventoryId)
    
    // 模拟数据
    setTimeout(() => {
      inventoryHistory.value = [
        {
          date: '2023-11-30 10:15:23',
          type: 'init',
          quantity: 100,
          reason: 'purchase',
          operator: '张三',
          remark: '首次入库',
          balance: 100
        },
        {
          date: '2023-12-05 14:32:10',
          type: 'adjust',
          quantity: -5,
          reason: 'loss',
          operator: '李四',
          remark: '库存盘点损耗',
          balance: 95
        },
        {
          date: '2023-12-10 09:45:36',
          type: 'use',
          quantity: -10,
          reason: 'prescription',
          operator: '王五',
          remark: '处方发药',
          balance: 85
        },
        {
          date: '2023-12-15 16:20:18',
          type: 'adjust',
          quantity: 5,
          reason: 'surplus',
          operator: '赵六',
          remark: '库存盘点盈余',
          balance: 90
        }
      ]
      historyLoading.value = false
    }, 1000)
  } catch (error) {
    console.error('获取库存历史记录失败', error)
    ElMessage.error('获取库存历史记录失败')
    historyLoading.value = false
  }
}

// 返回上一页
const goBack = () => {
  router.back()
}

// 判断药品是否已过期
const isExpired = (expiryDate) => {
  if (!expiryDate) return false
  
  const today = new Date()
  const expiry = new Date(expiryDate)
  
  return expiry < today
}

// 判断药品是否即将过期（距离过期不到30天）
const isNearExpiry = (expiryDate) => {
  if (!expiryDate) return false
  
  const remainingDays = calculateRemainingDays(expiryDate)
  return remainingDays > 0 && remainingDays <= 30
}

// 计算剩余天数
const calculateRemainingDays = (expiryDate) => {
  if (!expiryDate) return 0
  
  const today = new Date()
  const expiry = new Date(expiryDate)
  const diffTime = expiry - today
  return Math.ceil(diffTime / (1000 * 60 * 60 * 24))
}

// 获取有效期的CSS类
const getExpiryClass = (inventory) => {
  if (isExpired(inventory.expiryDate)) {
    return 'expired-text'
  } else if (isNearExpiry(inventory.expiryDate)) {
    return 'warning-text'
  }
  return ''
}

// 获取状态标签类型
const getStatusTagType = (inventory) => {
  if (isExpired(inventory.expiryDate)) {
    return 'danger'
  }
  
  if (isNearExpiry(inventory.expiryDate)) {
    return 'warning'
  }
  
  if (inventory.quantity <= inventory.minInventory) {
    return 'warning'
  }
  
  return 'success'
}

// 获取状态标签文本
const getStatusLabel = (inventory) => {
  if (isExpired(inventory.expiryDate)) {
    return '已过期'
  }
  
  if (isNearExpiry(inventory.expiryDate)) {
    return '即将过期'
  }
  
  if (inventory.quantity <= 0) {
    return '无库存'
  }
  
  if (inventory.quantity <= inventory.minInventory) {
    return '低库存'
  }
  
  return '正常'
}

// 获取操作类型标签类型
const getOperationTagType = (type) => {
  const typeMap = {
    'init': 'success',
    'adjust': 'warning',
    'use': 'info',
    'discard': 'danger'
  }
  return typeMap[type] || 'info'
}

// 获取操作类型标签文本
const getOperationLabel = (type) => {
  const typeMap = {
    'init': '入库',
    'adjust': '调整',
    'use': '使用',
    'discard': '报废'
  }
  return typeMap[type] || type
}

// 获取操作原因标签文本
const getReasonLabel = (reason, type) => {
  const reasonMap = {
    'purchase': '采购入库',
    'return': '退货入库',
    'adjustment': '调整入库',
    'surplus': '盘盈',
    'loss': '盘亏',
    'damage': '损耗',
    'prescription': '处方发药',
    'medical_order': '医嘱使用',
    'expired': '过期报废',
    'quality': '质量问题',
    'damaged': '包装破损',
    'other': '其他'
  }
  return reasonMap[reason] || reason
}

// 调整库存
const handleUpdateInventory = () => {
  inventoryDialog.form.id = inventoryId
  inventoryDialog.form.drugName = inventoryData.drugName
  inventoryDialog.form.batchNumber = inventoryData.batchNumber
  inventoryDialog.form.currentQuantity = inventoryData.quantity
  inventoryDialog.form.adjustQuantity = 0
  inventoryDialog.form.unit = inventoryData.unit
  inventoryDialog.form.reason = ''
  inventoryDialog.form.remark = ''
  inventoryDialog.visible = true
}

// 确认库存调整
const confirmInventoryAdjust = async () => {
  if (!inventoryDialog.form.reason) {
    ElMessage.warning('请选择调整原因')
    return
  }

  inventoryDialog.loading = true
  try {
    const res = await drugInventoryAPI.updateInventory(inventoryDialog.form.id, {
      adjustQuantity: inventoryDialog.form.adjustQuantity,
      reason: inventoryDialog.form.reason,
      remark: inventoryDialog.form.remark
    })
    
    if (res.data && res.data.success) {
      ElMessage.success('库存调整成功')
      inventoryDialog.visible = false
      fetchInventoryDetail()
      fetchInventoryHistory()
    } else {
      ElMessage.error(res.data.message || '库存调整失败')
    }
  } catch (error) {
    console.error('库存调整失败', error)
    ElMessage.error('库存调整失败')
  } finally {
    inventoryDialog.loading = false
  }
}

// 药品报废
const handleDiscard = () => {
  discardDialog.form.id = inventoryId
  discardDialog.form.drugName = inventoryData.drugName
  discardDialog.form.batchNumber = inventoryData.batchNumber
  discardDialog.form.currentQuantity = inventoryData.quantity
  discardDialog.form.discardQuantity = inventoryData.quantity
  discardDialog.form.unit = inventoryData.unit
  discardDialog.form.reason = isExpired(inventoryData.expiryDate) ? 'expired' : ''
  discardDialog.form.remark = isExpired(inventoryData.expiryDate) ? '药品已过期' : ''
  discardDialog.visible = true
}

// 确认报废
const confirmDiscard = async () => {
  if (!discardDialog.form.reason) {
    ElMessage.warning('请选择报废原因')
    return
  }

  discardDialog.loading = true
  try {
    const res = await drugInventoryAPI.updateInventory(discardDialog.form.id, {
      adjustQuantity: -discardDialog.form.discardQuantity,
      reason: 'discard',
      discardReason: discardDialog.form.reason,
      remark: discardDialog.form.remark
    })
    
    if (res.data && res.data.success) {
      ElMessage.success('药品报废成功')
      discardDialog.visible = false
      fetchInventoryDetail()
      fetchInventoryHistory()
    } else {
      ElMessage.error(res.data.message || '药品报废失败')
    }
  } catch (error) {
    console.error('药品报废失败', error)
    ElMessage.error('药品报废失败')
  } finally {
    discardDialog.loading = false
  }
}

// 生命周期钩子
onMounted(() => {
  fetchInventoryDetail()
  fetchInventoryHistory()
})
</script>

<style scoped>
.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-left {
  display: flex;
  align-items: center;
  gap: 10px;
}

.header-left h3 {
  margin: 0;
}

.info-section {
  margin-bottom: 30px;
}

.section-title {
  margin-bottom: 15px;
  padding-left: 10px;
  border-left: 4px solid #409EFF;
}

.inventory-count {
  font-weight: bold;
  font-size: 16px;
}

.warning-text {
  color: #E6A23C;
  font-weight: bold;
}

.expired-text {
  color: #F56C6C;
  font-weight: bold;
}

.quantity-increase {
  color: #67C23A;
}

.quantity-decrease {
  color: #F56C6C;
}
</style> 